const { exec } = require("../db/mysql");

function getList(author, keyword) {
  const sql = `select * from blogs where 1=1 `;
  if (author) {
    sql += `and author='${author}' `;
  }
  if (keyword) {
    sql += `and title like '%${keyword}%' `;
  }
  sql += "order by createtime desc;";

  // 返回promise
  return exec(sql);
}

function getDetail(id) {
  const sql = `select * from blogs where id='${id}';`;

  // 返回promise
  return exec(sql).then((rows) => {
    return rows[0];
  });
}

function newBlog(blogData = {}) {
  // blogData 是一个博客对象，包含title content author属性
  const { title, content, createtime = Date.now(), author } = blogData;
  const sql = `insert into blogs (title, content, createtime, author) values ('${title}', '${content}', ${createtime}, '${author}');`;
  return exec(sql).then((insertData) => {
    // console.log("insertData is ", insertData);
    return { id: insertData.insertId };
  });
}

function updateBlog(id, blogData = {}) {
  // console.log('blog update:', id, blogData)
  const { title, content } = blogData;
  const sql = `update blogs set title='${title}', content='${content}' where id='${id}';`;
  return exec(sql).then((updateData) => {
    // console.log("updateData is ", updateData);
    if (updateData.affectedRows > 0) {
      return true;
    }
    return false;
  });
}

function delBlog(id, author) {
  // console.log('blog delete:', id)
  const sql = `delete from blogs where id='${id}' and author='${author}';`;
  return exec(sql).then(delData=>{
    if (delData.affectedRows > 0) {
      return true;
    }
    return false;
  })
}

module.exports = {
  getList,
  getDetail,
  newBlog,
  updateBlog,
  delBlog,
};
